package com.itsq.controller.resources;


import com.alibaba.fastjson.JSONObject;
import com.itsq.common.bean.ErrorEnum;
import com.itsq.common.bean.Response;
import com.itsq.common.constant.APIException;
import com.itsq.config.UserConstantInterface;
import com.itsq.enums.EnumTokenType;
import com.itsq.pojo.dto.LoginRespDto;
import com.itsq.pojo.entity.User;
import com.itsq.service.resources.UserService;
import com.itsq.token.AuthToken;
import com.itsq.utils.wx.HttpClientUtil;
import io.swagger.annotations.Api;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
@Api(tags = "判断是否是新用户")
public class UserApi {

    @Autowired
    private UserService usersService;

    @PostMapping("/me/login")
    public Response<LoginRespDto<User>> user_login(
            @RequestParam("code") String code,
            @RequestParam("userHead") String userHead,
            @RequestParam("userName") String userName
    ){

        // 发送请求
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + UserConstantInterface.WX_LOGIN_APPID + "&secret=" + UserConstantInterface.WX_LOGIN_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        String openid = null;
        String accessToken = null;
        try {
            CloseableHttpClient client = null;
            client = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse resp = null;
            resp = client.execute(httpGet);
            if (resp.getStatusLine().getStatusCode() == 200) {
                String info = EntityUtils.toString(resp.getEntity(), "UTF-8");
                JSONObject obj = JSONObject.parseObject(info);
                openid = (String) obj.get("openid");
                accessToken = (String) obj.get("access_token");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 根据返回的user实体类，判断用户是否是新用户，不是的话，更新最新登录时间，是的话，将用户信息存到数据库
        User user = usersService.selectByOpenId(openid);
        if(user==null) {
            User insert_user = new User();
            insert_user.setVxCode(openid);
            insert_user.setHeadImage(userHead);
            insert_user.setName(userName);
            System.out.println("insert_user:" + insert_user.toString());
            // 添加到数据库
            Boolean flag = usersService.insertUsers(insert_user);
            if (!flag) {
                throw new APIException(ErrorEnum.USER_NOT_EXITES);
            }
            // 如果插入成功进行返回
            // 使用open_id进行查询
            User users = usersService.selectByOpenId(openid);

            String authToken = new AuthToken(users.getId(),users.getName()).token();
            return Response.success(new LoginRespDto<User>(users,authToken, EnumTokenType.BEARER.getCode()));
        }else{
            String authToken = new AuthToken(user.getId(),user.getName()).token();
            return Response.success(new LoginRespDto<User>(user,authToken, EnumTokenType.BEARER.getCode()));

        }

    }

//    @GetMapping("/me/login")
//    public void user_wxlogin(String code, String flag,
//                             HttpServletRequest request,
//                             HttpServletResponse response) throws IOException {
//
//
//        String urlInfo = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + UserConstantInterface.WX_LOGIN_APPID + "&secret=" + UserConstantInterface.WX_LOGIN_SECRET + "&code=" + code + "&grant_type=authorization_code";
//
//        try {
//            CloseableHttpClient client = null;
//            String openid = null;   http://
//            client = HttpClients.createDefault();
//            HttpGet httpGet = new HttpGet(urlInfo);
//            HttpResponse resp = null;
//            resp = client.execute(httpGet);
//            String accessToken = null;
//            if (resp.getStatusLine().getStatusCode() == 200) {
//                String info = EntityUtils.toString(resp.getEntity(), "UTF-8");
//                JSONObject obj = JSONObject.parseObject(info);
//                openid = (String) obj.get("openid");
//                accessToken = (String) obj.get("access_token");
//            }
//            LoginRespDto loginRespDto =null;
//            String authToken = null;
//            //使用openId处理用户注册或登录
//            User user = usersService.selectByOpenId(openid);
//            if (user == null) {
//                String name = "";//微信昵称
//                String weixImg = "";//微信头像
//                if (accessToken != null) {
//                    String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openid + "&lang=zh_CN";
//                    HttpGet httpGet2 = new HttpGet(infoUrl);
//                    resp = client.execute(httpGet2);
//                    if (resp.getStatusLine().getStatusCode() == 200) {
//                        String info = EntityUtils.toString(resp.getEntity(), "UTF-8");
//                        JSONObject obj = JSONObject.parseObject(info);
//                        name = obj.getString("nickname");
//                        weixImg = obj.getString("headimgurl");
//                    }
//                }
//
//                User insert_user = new User();
//                insert_user.setVxCode(openid);
//                insert_user.setHeadImage(weixImg);
//                insert_user.setName(name);
//                System.out.println("insert_user:" + insert_user.toString());
//                // 添加到数据库
//                Boolean flag1 = usersService.insertUsers(insert_user);
//                if (!flag1) {
//                    throw new APIException(ErrorEnum.USER_NOT_EXITES);
//                }
//                // 如果插入成功进行返回
//                // 使用open_id进行查询
//                User users = usersService.selectByOpenId(openid);
//                authToken = new AuthToken(users.getId(), users.getName()).token();
//
////               return Response.success();
//                loginRespDto =new LoginRespDto<User>(users, authToken, EnumTokenType.BEARER.getCode());
//
//            } else {
//                authToken = new AuthToken(user.getId(), user.getName()).token();
//                loginRespDto =new LoginRespDto<User>(user, authToken, EnumTokenType.BEARER.getCode());
//
//                //   return Response.success(new LoginRespDto<User>(user, authToken, EnumTokenType.BEARER.getCode()));
//
//            }
//
////            String url = "http://test.yuanqiwl.top/m/#/pages/appLogin/mpLogin?shuibian="+JSONObject.toJSONString(loginRespDto);
//            String url = "http://xzchenyou.com:8081/jiaoyu/#/pages/appLogin/mpLogin?shuibian=" + JSONObject.toJSONString(loginRespDto);
//            response.addHeader("X-Token", authToken);
//            response.sendRedirect(url);
////            switch (flag) {
////                case "1":
////                    //语句
////                    url="http://xzchenyou.com/chenyou/index.html";
////                    break; //可选
////                case "2":
////                    //语句
////                    url="";
////                    break; //可选
////                case "3":
////                    //语句
////                    url="";
////                    break; //可选
////                case "4":
////                    //语句
////                    url="";
////                    break; //可选
////                case "5":
////                    //语句
////                    url="";
////                    break; //可选
////
////            }
////
////            //判断页面跳转
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//    }

}